import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Card, Select, Input, AutoComplete, Anchor } from 'antd';
import queryString from 'query-string';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '@/utils/utils.less';
import Authorized from '@/utils/Authorized';
import BasicInfor from './BasicInfor';
import EntryInfor from './EntryInfor';
import SearchRecordInfor from './SearchRecordInfor';
import SocialHandleInfor from './SocialHandleInfor';
import RefundInfor from './RefundInfor';
import AccuHandleInfor from './AccuHandleInfor';
import SocialCardInfor from './SocialCardInfor';
import DimissInfor from './DimissInfor';
import PaymentInfor from './PaymentInfor';
import ArchivesInfor from './ArchivesInfor';
import LaborContractInfor from './LaborContractInfor';
import ProServiceInfor from './ProServiceInfor';
import Search from '@/components/AntDesign/Search';
import HOCSelect from '@/components/AntDesign/Select';

// const { Search } = Input;
const { Option } = Select;
const { Link } = Anchor;
const FormItem = Form.Item;

@connect(({ empIntegratedquery, loading }) => ({
  empIntegratedquery,
  loading: loading.models.empIntegratedquery,
  empShowName: empIntegratedquery.empShowName, // 员工显示的默认值
}))
@Form.create()
class SearchList extends PureComponent {
  state = {};

  componentDidMount() {
    const {
      location,
      empIntegratedquery: { empLabelObj },
    } = this.props;
    const { isMenuLink } = queryString.parse(location.search);
    if (isMenuLink) {
      this.resetAndGeLlist(location);
    } else if (empLabelObj) {
      const empKeyObj = empLabelObj.key;
      const empKeyArr = empKeyObj.split(' ');
      const empLabelObjs = empLabelObj.label;
      const empLabelArr = empLabelObjs.split(' ');
      this.setState({ empName: empLabelArr[0], certNo: empKeyArr[1] });
    }
  }

  // 清空数据
  delAllListData = () => {
    const { dispatch } = this.props;
    const opermars = {
      empList: [],
      empRecordInfo: { list: [] },
      empLaborContInfo: {},
      empDimissionInfo: { list: [] },
      empInsCardInfo: { list: [] },
      empAccuSerInfo: { list: [] },
      empInsRefundInfo: { list: [] },
      empInsSerInfo: { list: [] },
      consultInfo: { list: [] },
      empAccuPayInfo: { list: [] },
      empInsPayInfo: { list: [] },
      entryInfo: { list: [] },
      baseInfo: {},
      proServiceInfor: { list: [] },
      empLabelObj: undefined,
    };

    dispatch({
      type: 'empIntegratedquery/updateModalData',
      payload: opermars,
    });
  };

  // 跳转路由
  jumpRouting = (targetRouter, id) => {
    // 跳转
    let dynamicRouter;
    switch (targetRouter) {
      case 'socialPay':
        dynamicRouter = '/socialinsurancemanagement/insonline';
        break;
      case 'accuPay':
        dynamicRouter = '/providentfundmanagement/accuonline';
        break;
      case 'refundInfoId':
        dynamicRouter = '/fmmanage/rebate';
        break;
      case 'rcrdId':
        dynamicRouter = '/hrmanage/searchrecord';
        break;
      case 'insCardHdlId':
        dynamicRouter = '/socialinsurancemanagement/socialcard';
        break;
      case 'laborContId':
        dynamicRouter = '/careermanage/laborcontract';
        break;
      case 'rcrdSerHdlId':
        dynamicRouter = '/hrmanage/recordservice';
        break;
      case 'accuSerHdlId':
        dynamicRouter = '/providentfundmanagement/accuhandle';
        break;
      case 'insSerHdlId':
        dynamicRouter = '/socialinsurancemanagement/inshandle';
        break;
      case 'dimissionId':
        dynamicRouter = '/careermanage/dimission';
        break;
      case 'entryId':
        dynamicRouter = '/careermanage/career';
        break;
      default:
    }

    const { certNo, empName } = this.state;
    const routerParams = {
      pathname: id ? `${dynamicRouter}/detail` : `${dynamicRouter}/index`,
      query: {
        [targetRouter]: id,
        isMenuLink: false,
      },
      queryParam: { empName, certNo },
    };
    router.push(routerParams);
  };

  // 雇员搜索
  getEmpList = value => {
    const { dispatch } = this.props;
    // 判断字符串中包含空格，特殊字符
    const reg = /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/;
    let newValue = '';
    if (!reg.test(value)) {
      newValue = value.substring(value.indexOf('(') + 1, value.indexOf(')'));
    }
    dispatch({
      type: 'empIntegratedquery/fetchEmpList',
      payload: {
        keyword: newValue ? newValue.trim() : value.trim(),
      },
    });
  };

  // 选择某一雇员
  selectEmp = (value, options) => {
    const { dispatch } = this.props;
    const {
      key,
      fsOptions: { certNo, sendId, empName, empId },
    } = options;
    this.setState({ certNo, empName, addConFlag: true });
    dispatch({
      type: 'empIntegratedquery/updateModalData',
      payload: {
        empLabelObj: { key, label: `${empName} ${certNo}` },
        empShowName: value,
      },
    });

    // 员工基本信息
    dispatch({
      type: 'empIntegratedquery/fetchBaseInfo',
      payload: {
        certNo, // 雇员id
      },
    });
    // 产品服务信息
    dispatch({
      type: 'empIntegratedquery/fetchProServiceInfo',
      payload: {
        sendId, // 雇员id
      },
    });
    // 入职办理
    dispatch({
      type: 'empIntegratedquery/fetchEntryInfo',
      payload: {
        certNo, // 雇员id
      },
    });

    // 社保实缴查询
    dispatch({
      type: 'empIntegratedquery/fetchEmpInsPayInfo',
      payload: {
        certNo, // 雇员身份证号
      },
    });
    // 公积金实缴查询
    dispatch({
      type: 'empIntegratedquery/fetchEmpAccuPayInfo',
      payload: {
        certNo,
      },
    });
    // 咨询记录
    dispatch({
      type: 'empIntegratedquery/fetchConsultInfo',
      payload: {
        certNo, // 雇员id
      },
    });

    // 社保服务办理
    dispatch({
      type: 'empIntegratedquery/fetchEmpInsSerInfo',
      payload: {
        certNo, // 雇员身份证号
      },
    });
    // 返款信息
    dispatch({
      type: 'empIntegratedquery/fetchEmpInsRefundInfo',
      payload: {
        pageArg: { currentPage: 1, pageSize: 2 },
        certNo, // 雇员身份证号
      },
    });
    // 公积金服务办理
    dispatch({
      type: 'empIntegratedquery/fetchEmpAccuSerInfo',
      payload: {
        certNo, // 雇员id
      },
    });
    // 社保卡办理
    dispatch({
      type: 'empIntegratedquery/fetchEmpInsCardInfo',
      payload: {
        certNo, // 雇员id
      },
    });
    // 离职联系
    dispatch({
      type: 'empIntegratedquery/fetchEmpDimissionInfo',
      payload: {
        certNo, // 雇员id
      },
    });

    // 劳动合同信息
    dispatch({
      type: 'empIntegratedquery/fetchEmpLaborContInfo',
      payload: {
        empId,
      },
    });
    // 档案服务办理
    dispatch({
      type: 'empIntegratedquery/fetchEmpRecordInfo',
      payload: {
        certNo, // 雇员id
      },
    });
  };

  // 咨询记录刷新
  getConsultInfoList = flag => {
    const { dispatch } = this.props;
    const { certNo } = this.state;
    if (flag) {
      // 咨询记录
      dispatch({
        type: 'empIntegratedquery/fetchConsultInfo',
        payload: {
          certNo,
        },
      });
    }
  };

  // 重置查询条件并获取列表
  async resetAndGeLlist(location) {
    const { dispatch, form } = this.props;
    dispatch({
      type: 'global/changeIsMenuLink',
      payload: location,
    });
    await this.delAllListData();
    form.resetFields();
  }

  render() {
    const { empIntegratedquery, form, empShowName } = this.props;
    const { certNo } = this.state;
    const addConFlag = empShowName ? true : this.state.addConFlag
    const { getFieldDecorator } = form;
    let options = null;
    if (empIntegratedquery.empList && empIntegratedquery.empList.length) {
      options = empIntegratedquery.empList.map(opt => (
        <Option
          key={`${opt.empId} ${opt.certNo}`}
          value={`${opt.empName} (${opt.certNo})`}
          fsOptions={opt}
        >
          {`${opt.empName} (${opt.certNo})`}
        </Option>
      ));
    }
    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard} style={{ marginBottom: 0 }}>
          <div>
            <Row>
              <Col span={12} offset={6}>
                <HOCSelect
                  defaultValue="1"
                  style={{
                    borderRadius: '0 4px 4px 0',
                    display: 'inline-block',
                    marginRight: -2,
                    fontSize: 14,
                    float: 'left',
                    marginTop: '-4px',
                  }}
                  size="large"
                >
                  <Option key={1}>员工</Option>
                </HOCSelect>
                <FormItem style={{ float: 'left', width: '75%' }}>
                  {getFieldDecorator('empForm', {
                    initialValue: empShowName,
                  })(
                    <AutoComplete
                      size="large"
                      style={{ width: '100%' }}
                      dataSource={options}
                      onSelect={this.selectEmp}
                      labelInValue
                    >
                      <Search
                        placeholder="请输入"
                        enterButton="搜索"
                        size="large"
                        style={{ width: '100%', marginTop: '-5px' }}
                        onSearch={value => this.getEmpList(value)}
                      />
                    </AutoComplete>
                  )}
                </FormItem>
              </Col>
            </Row>
          </div>
        </Card>
        <div className={styles.antAnchorDefaultBg}>
          <Anchor onClick={e => e.preventDefault()} style={{ background: '#f0f2f5' }}>
            <Row className={styles.flexOver}>
              <Row type="flex">
                <Col>
                  <Link href="#basicInfor" title="基本信息" />
                </Col>
                <Col>
                  <Link href="#proserviceinfor" title="产品服务信息" />
                </Col>
                <Authorized authority="es:career:entryhandle" noMatch={null}>
                  <Col>
                    <Link href="#entryInfor" title="入职办理" />
                  </Col>
                </Authorized>
                <Authorized authority="business:social:query" noMatch={null}>
                  <Col>
                    <Link href="#paymentinsInfor" title="社保实缴信息" />
                  </Col>
                </Authorized>
                <Authorized authority="business:provident:query" noMatch={null}>
                  <Col>
                    <Link href="#paymentaccuInfor" title="公积金实缴信息" />
                  </Col>
                </Authorized>
                <Authorized authority="es:per:searchrecord" noMatch={null}>
                  <Col>
                    <Link href="#searchRecordInfor" title="咨询记录" />
                  </Col>
                </Authorized>
                <Authorized authority="business:social:handle" noMatch={null}>
                  <Col>
                    <Link href="#socialHandleInfor" title="社保服务办理" />
                  </Col>
                </Authorized>
                <Authorized authority="business:fm:rebate" noMatch={null}>
                  <Col>
                    <Link href="#refundInfor" title="返款信息" />
                  </Col>
                </Authorized>
                <Authorized authority="business:provident:handle" noMatch={null}>
                  <Col>
                    <Link href="#accuHandleInfor" title="公积金服务办理" />
                  </Col>
                </Authorized>
                <Authorized authority="business:social:socialcard" noMatch={null}>
                  <Col>
                    <Link href="#socialCardInfor" title="社保卡办理" />
                  </Col>
                </Authorized>
                <Authorized authority="es:career:dimission" noMatch={null}>
                  <Col>
                    <Link href="#dimissInfor" title="离职联系" />
                  </Col>
                </Authorized>
                <Authorized authority="es:career:laborcontract" noMatch={null}>
                  <Col>
                    <Link href="#laborContractInfor" title="劳动合同信息" />
                  </Col>
                </Authorized>
                <Authorized authority="es:per:archives" noMatch={null}>
                  <Col>
                    <Link href="#archivesInfor" title="档案服务办理" />
                  </Col>
                </Authorized>
              </Row>
            </Row>
          </Anchor>
        </div>
        <BasicInfor baseInfo={empIntegratedquery.baseInfo} />
        <ProServiceInfor proServiceInfor={empIntegratedquery.proServiceInfor} />
        <Authorized authority="es:career:entryhandle" noMatch={null}>
          <EntryInfor entryInfo={empIntegratedquery.entryInfo} jumpRouting={this.jumpRouting} />
        </Authorized>
        <Authorized
          authority={['business:social:query', 'business:provident:query']}
          noMatch={null}
        >
          <PaymentInfor
            empInsPayInfo={empIntegratedquery.empInsPayInfo}
            empAccuPayInfo={empIntegratedquery.empAccuPayInfo}
            jumpRouting={this.jumpRouting}
          />
        </Authorized>
        <Authorized authority="es:per:searchrecord" noMatch={null}>
          <SearchRecordInfor
            certNo={certNo}
            getConsultInfoList={this.getConsultInfoList}
            addConFlag={addConFlag}
            consultInfo={empIntegratedquery.consultInfo}
            jumpRouting={this.jumpRouting}
          />
        </Authorized>
        <Authorized authority="business:social:handle" noMatch={null}>
          <SocialHandleInfor
            empInsSerInfo={empIntegratedquery.empInsSerInfo}
            jumpRouting={this.jumpRouting}
          />
        </Authorized>
        <Authorized authority="business:fm:rebate" noMatch={null}>
          <RefundInfor
            empInsRefundInfo={empIntegratedquery.empInsRefundInfo}
            jumpRouting={this.jumpRouting}
          />
        </Authorized>
        <Authorized authority="business:provident:handle" noMatch={null}>
          <AccuHandleInfor
            empAccuSerInfo={empIntegratedquery.empAccuSerInfo}
            jumpRouting={this.jumpRouting}
          />
        </Authorized>
        <Authorized authority="business:social:socialcard" noMatch={null}>
          <SocialCardInfor
            empInsCardInfo={empIntegratedquery.empInsCardInfo}
            jumpRouting={this.jumpRouting}
          />
        </Authorized>
        <Authorized authority="es:career:dimission" noMatch={null}>
          <DimissInfor
            empDimissionInfo={empIntegratedquery.empDimissionInfo}
            jumpRouting={this.jumpRouting}
          />
        </Authorized>
        <Authorized authority="es:career:laborcontract" noMatch={null}>
          <LaborContractInfor
            empLaborContInfo={empIntegratedquery.empLaborContInfo}
            jumpRouting={this.jumpRouting}
          />
        </Authorized>
        <Authorized authority="es:per:archives" noMatch={null}>
          <ArchivesInfor
            empRecordInfo={empIntegratedquery.empRecordInfo}
            jumpRouting={this.jumpRouting}
          />
        </Authorized>
      </PageHeaderWrapper>
    );
  }
}

export default SearchList;
